package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.RoleMapper;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.query.QueryObject;
import cn.wolfcode.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
@Autowired
    private RoleMapper roleMapper;
    @Override
    public void save(Role role) {
        roleMapper.insert(role);
    }

    @Override
    public void delete(Long id) {
        roleMapper.deleteByPrimaryKey(id);

    }

    @Override
    public void update(Role role) {
        roleMapper.updateByPrimaryKey(role);
    }

    @Override
    public Role get(Long id) {
        Role role = roleMapper.selectByPrimaryKey(id);
        return role;
    }

    @Override
    public List<Role> listAll() {
        List<Role> list = roleMapper.selectAll();
        return list;
    }

    @Override
    public PageResult<Role> query(QueryObject qo) {
        int count = roleMapper.selectForCount(qo);
        if(count == 0){
            return new PageResult<Role>(qo.getCurrentPage(),qo.getPageSize(),count,Collections.emptyList());
        }
        int totalPage = count % qo.getPageSize() == 0 ? count/qo.getPageSize() : count/qo.getPageSize()+1;
        if(qo.getCurrentPage() > totalPage){
            qo.setCurrentPage(totalPage);
        }

        List<Role> roles = roleMapper.selectForList(qo);
        return new PageResult<Role>(qo.getCurrentPage(),qo.getPageSize(),count,roles);
    }
}
